from  flask import Flask
from flask_sqlalchemy import SQLAlchemy
app=Flask(__name__)


class Config(object):
    """配置参数"""
    #sqlalchemy的配置参数
    SQLALCHEMY_DATABASE_URI="mysql://root:123456@127.0.0.1:3306/python_demo"
    #设置sqlalchemy自动跟踪数据库
    SQLALCHEMY_TRACK_MODIFICATIONS=True
app.config.from_object(Config)


db=SQLAlchemy(app)

class Book(db.Model):
    """用户角色/身份表"""
    __tablename__="book"
    id=db.Column(db.Integer,primary_key=True)
    name=db.Column(db.String(32),unique=False)
    price=db.Column(db.Float(),unique=False)

@app.route('/add')
def addBook():
    print("addBook test")
    b = Book()
    b.id=1
    b.name = 'HelloJava'
    b.price = 12
    db.session.add(b)
    db.session.commit()
    return "add succ, here should be a form ,but i am to lazy! "

@app.route('/remove')
def removeBook():
    print("removeBook test")
    user=Book.query.get(1)
    db.session.delete(user)
    db.session.commit()
    return "remove succ"

@app.route('/edit')
def editBook():
    print("editBook test")
    user=Book.query.get(1)
    user.name = "helloWang"
    db.session.commit()
    return "edit succ "

@app.route('/show')
def showBook():
    print("show book test")
    user=Book.query.get(1)
    if user is None:
        return "no such book"
    return " id = %d , name = %s , price = %f " %(user.id,user.name,user.price)


@app.route('/')
def index():
    return '''
    <html>
    <body>
        <a href='/add'>add book </a> <br>
        <a href='/show'>show book </a><br>
        <a href='/edit'>edit book </a><br>
        <a href='/remove'>remove book </a><br>
    '''


if __name__ == '__main__':
    app.run(host='0.0.0.0',debug=True)